package com.fly.simple.task;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.SystemUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.CustomizableThreadFactory;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * ScheduleJob
 * 
 * @author 00fly
 * @version [版本号, 2022年11月30日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Slf4j
@Configuration
@ConditionalOnExpression("${system.job.index}==3")
public class ScheduleJob
{
    @Scheduled(fixedRate = 10 * 1000L)
    public void run()
    {
        try
        {
            log.info("Hello ScheduleJob!");
            String[] command = {"dir", "ls"};
            Executor.execute(command).forEach(System.out::println);
        }
        catch (IOException e)
        {
            log.error(e.getMessage(), e);
        }
    }
    
    @Bean
    ScheduledExecutorService scheduledExecutorService()
    {
        // return Executors.newScheduledThreadPool(10);
        return new ScheduledThreadPoolExecutor(10, new CustomizableThreadFactory("schedule-pool-"));
    }
}

@Slf4j
class Executor
{
    public static final boolean IS_OS_WINDOWS = SystemUtils.IS_OS_WINDOWS;
    
    /**
     * execute命令
     * 
     * @param command
     * @throws IOException
     * @see [类、类#方法、类#成员]
     */
    public static List<String> execute(String[] command)
        throws IOException
    {
        List<String> resultList = new ArrayList<>();
        String[] cmd = IS_OS_WINDOWS ? new String[] {"cmd", "/c", command[0]} : new String[] {"sh", "-c", command[1]};
        Process ps = Runtime.getRuntime().exec(cmd);
        log.info("========>>>>> 即将执行命令：{}", StringUtils.join(cmd, " "));
        try (BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream(), "GBK")))
        {
            String line;
            while ((line = br.readLine()) != null)
            {
                resultList.add(line);
            }
        }
        return resultList;
    }
}
